package com.lrj.mysecurity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lrj.mysecurity.dao.PermissionDao;
import com.lrj.mysecurity.dao.RoleDao;
import com.lrj.mysecurity.dao.RolePermissionDao;
import com.lrj.mysecurity.dao.UserDao;
import com.lrj.mysecurity.entity.*;
import com.lrj.mysecurity.service.UserRoleService;
import com.lrj.mysecurity.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private RolePermissionDao rolePermissionDao;

    @Autowired
    private PermissionDao permissionDao;

    @Override
    public User getById(Long id) {
        return userDao.selectById(id);
    }

    @Override
    public User getByName(String userName) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(UserConstant.COLUMN_NAMW, userName);
        return userDao.selectOne(queryWrapper);
    }

    @Override
    public List<Long> getRoleIdListByUserId(Long userId) {
        //获取角色id列表
        List<Long> roleIdList = userRoleService.getRoleIdListByUserId(userId);
        return roleIdList;
    }

    /**
     * 根据用户id获取角色列表
     * @param userId
     */
    @Override
    public List<Role> getRoleListByUserId(long userId) {
        List<Long> roleIdList = getRoleIdListByUserId(userId);
        if (roleIdList != null && roleIdList.size() > 0) {
            List<Role> roleList = roleDao.selectBatchIds(roleIdList);
            return roleList;
        }

        return null;
    }

    @Override
    public List<Long> getPermissionIdListByUserId(Long userId) {
        //获取角色id列表
        List<Long> roleIdList = getRoleIdListByUserId(userId);
        if (roleIdList != null && roleIdList.size() > 0) {
            QueryWrapper<RolePermission> queryWrapper = new QueryWrapper();
            queryWrapper.in(RolePermissionConstant.COLUMN_ROLE_ID, roleIdList);
            List<RolePermission> rolePermissionList = rolePermissionDao.selectList(queryWrapper);

            List<Long> permissionIdList = rolePermissionList.stream().map(rolePermission -> rolePermission.getPermissionId()).collect(Collectors.toList());
            return permissionIdList;
        }

        return null;
    }

    @Override
    public List<Permission> getPermissionListByUserId(Long userId) {
        List<Long> permissionIdList = getPermissionIdListByUserId(userId);
        if (permissionIdList != null && permissionIdList.size() > 0) {
            List<Permission> permissionList = permissionDao.selectBatchIds(permissionIdList);
            return permissionList;
        }

        return null;
    }
}
